﻿package adpter
{
	import adapter.common.AdapterBase;
	
	import adpter.layer.MapLayerAdapter;
	import adpter.layer.RoleLayerAdapter;
	
	import datapool.event.EventObject;
	import datapool.global.GlobalInfo;
	
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import ui.GameUI;
	
	public class GameUIAdapter extends AdapterBase
	{		
		private var _maplayerAdapter:MapLayerAdapter;
		private var _rolelayerAdapter:RoleLayerAdapter;

		//hight,width表示当前窗口的大小 x,y表示当前玩家所在的位置        
		
		public function GameUIAdapter()
		{
			super();
			init();
		}
		
		private function init():void
		{
			_maplayerAdapter = new MapLayerAdapter();
			_maplayerAdapter.parentAdapter = this;
			_rolelayerAdapter = new RoleLayerAdapter();
		}
		
		protected function get uiGameUI():GameUI
		{
			return ui as GameUI;
		}
		
		override protected function onUIAttach():void
		{
			super.onUIAttach();
			
			if(uiGameUI)
			{
				uiGameUI.updateMapLayerAdapter(_maplayerAdapter);
				uiGameUI.updateRoleLayerAdapter(_rolelayerAdapter);
			}
			
			context.eventMgr.addEventListener(EventObject.EVENT_PLAYER_POSTION_UPDATE, onPlayerPositionUpdate);
		}
		
		override protected function onUIDeattach():void
		{
			context.eventMgr.removeEventListener(EventObject.EVENT_PLAYER_POSTION_UPDATE, onPlayerPositionUpdate);
			_maplayerAdapter.deattachUI();
			_rolelayerAdapter.deattachUI();
			
			super.onUIDeattach();
		}
		
		public function update():void
		{
			_maplayerAdapter.update();
			_rolelayerAdapter.update();
		}
		
		public function gotoPos(pos:Point):void
		{
			_rolelayerAdapter.gotoPos(pos);
		}
		
		public function updatePlayerPostion(point:Point):void
		{
			var topleft:Point;
			topleft = caculateViewRect(point.x, point.y);
			_maplayerAdapter.updateViewRect();
			_rolelayerAdapter.updateViewRect();	
		}
		
		public function onPlayerPositionUpdate(e:EventObject):void
		{
//			trace(this, "onViewUpdate", e.param);
			var pos:Point = e.param as Point;
			if(pos)
			{
				updatePlayerPostion(pos);
			}
		}
		
		private function caculateViewRect(x:int, y:int):Point
		{
			var pos:Point = new Point;
			if(x <= GlobalInfo.stageWidth/2)
			{
				pos.x = 0;
			}
			else if(x >= MapLayerAdapter.mapWidth-GlobalInfo.stageWidth/2)
			{
				pos.x = MapLayerAdapter.mapWidth-GlobalInfo.stageWidth/2;
			}
			else
			{
				pos.x = x-GlobalInfo.stageWidth/2;
			}
			
			if(y <= GlobalInfo.stageWidth/2)
			{
				pos.y = 0;
			}
			else if(y >= MapLayerAdapter.mapHight-GlobalInfo.stageWidth/2)
			{
				pos.y = MapLayerAdapter.mapHight-GlobalInfo.stageWidth/2;
			}
			else
			{
				pos.y = y-GlobalInfo.stageWidth/2;
			}
			
			return pos;
		}
	}
}